var VIEW = VIEW || {};

VIEW.dom = VIEW.dom ||
(function () {
	return {
		setFocus: function (formId, hide) {
			var expr = (hide ? ":input:enabled:visible" : ":input:enabled");
			var target = null;
			$("#" + formId).find(expr).each(function() {
				if (!target) {
					if (0 <= this.tabIndex || $(this).hasClass("E_")) {
						target = this;
					}
				} else if (!$(target).hasClass("E_")) {
					if ($(this).hasClass("E_")) {
						target = this;
					} else if (0 < this.tabIndex) {
						if (target.tabIndex <= 0) {
							target = this;
						} else if (this.tabIndex < target.tabIndex) {
							target = this;
						}
					}
				}
				if (-100 === this.tabIndex) {
					this.tabIndex = 0;
				}
			});

			if (target) {
				if (!hide && !$(target).is(':visible')) {
					for (var ele = $(target); typeof ele.parent() !== 'undefined'; ele = ele.parent()) {
						if (ele.css('display') === 'none') {
							ele.show();
							break;
						}
					}
				}
				$(target).focus();
				if ($(target).attr("type") === "text") {
					$(target).select();
				}
			}
		},
		loadOptions: function (req, tid) {
			var did = Array.prototype.slice.call(arguments).slice(2);

			var clearOptions = function(id) {
				var target = (typeof id === 'string' ? document.getElementById(id) : id);
				while (target && 0 < target.length &&
						(target.length !== 1 || target.options[target.length - 1].value !== "")) {
					target.options[target.length - 1] = null;
				}
			};

			var setOptions = function(id, lbl, val) {
				var target = (typeof id === 'string' ? document.getElementById(id) : id);
				if (target) {
					var frag = document.createDocumentFragment();
					for (var i = 0, len = lbl.length; i < len; i += 1) {
						var opt = document.createElement("option");
						opt.setAttribute("value", val[i]);
						opt.appendChild(document.createTextNode(lbl[i]));
						frag.appendChild(opt);
					}
					target.appendChild(frag);
				}
			};

			var successCallback = function(response) {
				var list = $.parseJSON(response);
				setOptions(tid, list[0], list[1]);
			};

			clearOptions(tid);
			for (var i = 0, len = did.length; i < len; i += 1) {
				clearOptions(did[i]);
			}

			// for jquery
			$.ajax({type:"get", url:req, dataType:"text", success:successCallback});
		}
	};
}());
